package cn.org.processor.guestbook.api.interceptor;

import annotation.UserRoleIs;
import annotation.UserStatusCheck;
import cn.org.processor.guestbook.api.util.InterceptorResponseUtil;
import entity.User;
import io.Response;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 用户权限拦截器
 */
@Component
public class UserAuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod))
            return true;

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        User user = (User) request.getAttribute("current_user");
        Class<?> clazz = handlerMethod.getBean().getClass();
        // 用户类型拦截
        if (method.isAnnotationPresent(UserRoleIs.class) || clazz.isAnnotationPresent(UserRoleIs.class)) {
            UserRoleIs annotation = method.getAnnotation(UserRoleIs.class);

            if (user.getRole() != annotation.value()) {
                Response resp = Response.builder().ret(Response.Ret.FAILURE).msg("您的权限不足，无法访问").build();
                InterceptorResponseUtil.response(response, resp);
                return false;
            }
        }

        // 用户状态拦截
        if (method.isAnnotationPresent(UserStatusCheck.class) || clazz.isAnnotationPresent(UserStatusCheck.class)) {
            if (user.getStatus() != User.Status.NORMAL) {
                Response resp = Response.builder().ret(Response.Ret.FAILURE).msg("您的账号状态异常，无法访问").build();
                InterceptorResponseUtil.response(response, resp);
                return false;
            }
        }

        return true;
    }
}
